package com.longcheer.weibo;

import com.longcheer.weibo.api.StatusesApi;
import com.longcheer.weibo.util.Utils;
import com.longcheer.weibo.vo.Count;
import com.longcheer.weibo.vo.Status;
import com.weibo.net.WeiboException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;

public class DetailWeiboActivity extends Activity {
    
    private static final String TAG = "DetailWeiboActivity";
    
    private LinearLayout mUser;
    private ImageView mAvatar;
    private TextView mNick;
    private TextView mContent;
    private ImageView mImage;
    private LinearLayout mRepost;
    private TextView mRepostContent;
    private ImageView mRepostImage;
    private Button mRepostNum;
    private Button mCommentNum;
    private TextView mTime;
    private TextView mSource;
    
    private Status mStatus;

    private static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
    
    private Count mCount = new Count();
    
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mRepostNum.setText("" + mCount.reposts);
            mCommentNum.setText("" + mCount.comments);
            mRepostNum.invalidate();
            mCommentNum.invalidate();
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.detail_weibo);
        getViewsFromResource();
        
        Bundle data = getIntent().getExtras();
        mStatus = (Status)data.getSerializable("status");
        setViewsContent(mStatus);
        
        mUser.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startProfilActivity();
            }
        });
        
        mImage.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                startDetailImageActivity(mStatus.getOriginalPic());
            }
        });
        
        mRepostImage.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                startDetailImageActivity(mStatus.getRetweetedStatus().getOriginalPic());
            }
        });
        
        new Thread() {
            @Override
            public void run() {
                try {
                    Count c = StatusesApi.getRepostAndCommentCount(
                            DetailWeiboActivity.this, mStatus.getId());
                    if (c != null) {
                        mCount = c;
                        mHandler.sendEmptyMessage(0);
                    }
                } catch (WeiboException e) {
                    Log.e(TAG, "Get repost and comment count error.", e);
                }
            }
        }.start();
    }
    
    private void startProfilActivity() {
        Intent intent = new Intent().setClass(this, ProfileActivity.class);
        intent.putExtra("user", mStatus.getUser());
        startActivity(intent);
    }
    
    private void startDetailImageActivity(String srcPic) {
        Intent intent = new Intent().setClass(this, DetailImageActivity.class);
        intent.putExtra("large_url", srcPic);
        startActivity(intent);
    }

    private void getViewsFromResource() {
        mUser = (LinearLayout)findViewById(R.id.ll_detail_user);
        mAvatar = (ImageView)findViewById(R.id.iv_user_avatar);
        mNick = (TextView)findViewById(R.id.tv_detail_nick);
        mContent = (TextView)findViewById(R.id.tv_detail_content);
        mImage = (ImageView)findViewById(R.id.iv_detail_content);
        mRepost = (LinearLayout)findViewById(R.id.ll_detail_repost);
        mRepostContent = (TextView)findViewById(R.id.tv_detail_content_repost);
        mRepostImage = (ImageView)findViewById(R.id.iv_detail_content_repost);
        mRepostNum = (Button)findViewById(R.id.tv_detail_repost_num);
        mCommentNum = (Button)findViewById(R.id.tv_detail_comment_num);
        mTime = (TextView)findViewById(R.id.tv_detail_time);
        mSource = (TextView)findViewById(R.id.tv_detail_source);
    }
    
    private void setViewsContent(Status status) {
        String avatarUrl = status.getUser().getProfileImageUrl();
        if (!Utils.isEmpty(avatarUrl)) {
            ImageManager.getInstance().loadImage(avatarUrl, new ImageManager.Callback() {
                @Override
                public void imageLoaded(Bitmap bitmap, String imageUrl) {
                    mAvatar.setImageBitmap(bitmap);
                }
            });
        } else {
            mAvatar.setImageResource(R.drawable.ic_launcher);
        }
        
        mNick.setText(status.getUser().getScreenName());
        mContent.setText(status.getText());
        String imageUrl = status.getBmiddlePic();
        if (Utils.isEmpty(imageUrl)) {
            mImage.setVisibility(View.GONE);
        } else {
            mImage.setImageResource(R.drawable.preview_pic_loading);
            ImageManager.getInstance().loadImage(imageUrl, ImageManager.MIDDLE_IMAGE, new ImageManager.Callback() {
                @Override
                public void imageLoaded(Bitmap bitmap, String imageUrl) {
                    mImage.setImageBitmap(bitmap);
                }
            });
        }
        
        Status retweet = status.getRetweetedStatus();
        if (retweet == null) {
            mRepost.setVisibility(View.GONE);
        } else {
            mRepostContent.setText(retweet.getText());
            String repostImage = retweet.getBmiddlePic();
            if (Utils.isEmpty(repostImage)) {
                mRepostImage.setVisibility(View.GONE);
            } else {
                mRepostImage.setImageResource(R.drawable.preview_pic_loading);
                ImageManager.getInstance().loadImage(repostImage, ImageManager.MIDDLE_IMAGE, new ImageManager.Callback() {
                    @Override
                    public void imageLoaded(Bitmap bitmap, String imageUrl) {
                        mRepostImage.setImageBitmap(bitmap);
                    }
                });
            }
        }
        
        if (status.getRepostsCount() == -1) {
            mRepostNum.setText("0");
        } else {
            mRepostNum.setText("" + status.getRepostsCount());
        }
        
        if (status.getCommentsCount() == -1) {
            mCommentNum.setText("0");
        } else {
            mCommentNum.setText("" + status.getCommentsCount());
        }
        
        mTime.setText(sdf.format(status.getCreatedAt()));
        String srcText = String.format("%s%s", getResources().getText(R.string.from), 
                status.getSource().getShow());
        mSource.setText(srcText);
    }

    @Override
    public void onBackPressed() {
        recycleImage();
        super.onBackPressed();
    }
    
    private void recycleImage() {
        if (!Utils.isEmpty(mStatus.getBmiddlePic())) {
            ImageManager.getInstance().removeBitmap(mStatus.getBmiddlePic());
            Log.d(TAG, "recycle image:" + mStatus.getBmiddlePic());
        }
        
        Status retweet = mStatus.getRetweetedStatus();
        if (retweet != null && !Utils.isEmpty(retweet.getBmiddlePic())) {
            ImageManager.getInstance().removeBitmap(retweet.getBmiddlePic());
            Log.d(TAG, "recycle retweet image:" + retweet.getBmiddlePic());
        }
    }

}
